package com.readytocloud.r2cSoonSite;

import javax.jdo.PersistenceManager;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;
import net.sf.jsr107cache.CacheFactory;
import java.util.logging.Logger;
import com.google.appengine.api.memcache.stdimpl.GCacheFactory;

public class NoteRepository 
{
	private PersistenceManager pm = PMF.get().getPersistenceManager();
	private static final Logger log = Logger.getLogger(NoteRepository.class.getName());
	
	private Cache cache;
	
	private String query = "select from " + SmallNote.class.getName();
	
	
	public NoteRepository()
	{
		query = "select  from " + SmallNote.class.getName();
		HashMap<Integer, Integer> cacheProp = new HashMap<Integer, Integer>();
		cacheProp.put(GCacheFactory.EXPIRATION_DELTA, 10);
		try 
		{
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			cache = cacheFactory.createCache(cacheProp);
		}
		catch (CacheException e)
		{
			log.info(e.getMessage());
		}
	}
	
	public void setQuery(String sQuery)
	{
		this.query = sQuery;
	}
	
	@SuppressWarnings("unchecked")
	public List<SmallNote> GetNotes()
	{
		List<SmallNote> notes = new ArrayList<SmallNote>();
		notes = (ArrayList<SmallNote>)cache.get(1);
		if(notes==null)
		{
			notes = (List<SmallNote>) pm.newQuery(query).execute();
			ArrayList<SmallNote> cNotes = new ArrayList<SmallNote>();
			cNotes.addAll(notes);
			cache.put(1, cNotes);
		}
		return notes;
	}
	
	public void Close()
	{
		pm.close();
	}
	
	
}
